<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/26
 * Time: 14:40
 */

namespace AdminsBundle\Controller;

use AdminsBundle\Entity\Page as Entity;
use AdminsBundle\Entity\PageProduce;
use AdminsBundle\Entity\PageShow;
use AdminsBundle\Helper\MyForms;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use AdminsBundle\Helper\MyController;

class PageController extends MyController{

    /*快速复制项目通用化配置*/
    private $entity;
    private $entityName = "Page";
    private $listKeys = array("id","title","count","updateTime","orders");
    private $searchKeys = array("title");
    private $conditionKeys = array("");
    private $editKeys = array("orders");
    private $perPage = 10;

    /**
     * @route("Page/add",name="PagePreAdd")
     */
    public function add()
    {
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName , $this->entity,   $this->generateUrl($this->entityName."DoAdd"));
        $show = $form->createView();
        $data = array(
            "title" => "新增单页",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Page/add/do",name="PageDoAdd")
     *
     * @Method({"GET", "POST"})
     */
    public function doAdd(Request $request)
    {
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName ,  $this->entity);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $this->entity->setAddTime(time());
            $em->persist($this->entity);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreAdd"),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Page/edit/{id}",name="PagePreEdit")
     */
    public function edit(Entity $entity)
    {
        $action = $this->generateUrl($this->entityName."DoEdit",array("id"=>$entity->getId()));
        $form = $this->createMyForm($this->entityName ,  $entity ,  $action );
        $show = $form->createView();
        $data = array(
            "title" => "管理单页",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Page/edit/{id}/do",name="PageDoEdit")
     *
     * @Method({"GET", "POST"})
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $form = $this->createMyForm($this->entityName ,  $entity );
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreEdit",array("id"=>$entity->getId())),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Page",name="PageLists")
     */
    public function lists()
    {
        /*分页配置*/
        if ($page   = $this->getParamRequired("page")){} else { $page = 1;}
        $per_page   = $this->perPage;

        $lists = $this->getLists($page,$per_page);
        $total = $lists["total"];

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl($this->entityName."Tools"),
            "addUrl"=>$this->generateUrl($this->entityName."PreAdd"),
        );

        return $this->render("AdminsBundle:".$this->entityName.":list.php.twig", array(
            'title'     => "单页列表",
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl($this->entityName."Lists"),$total,$per_page),
        ));
    }

    /**
     * @route("Page/tools",name="PageTools")
     */
    public function tools(Request $request)
    {

        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out($this->entityName."Lists","参数丢失");
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out($this->entityName."Lists","参数丢失");
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    $this->entity  = $em->find("AdminsBundle:".$this->entityName,$id);
                    $em->remove($this->entity);
                }
                $em->flush();
            }
        }
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $this->entity  = $em->find("AdminsBundle:".$this->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->editKeys ) ) { continue; }
                    $func = "set$key";
                    $this->entity->$func($val);
                }
                $em->persist($this->entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        return $this->redirect($this->generateUrl($this->entityName."Lists")."?".$queryStr);
    }
    private function getLists($page,$per_page)
    {
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        $qb = $this
            ->getDoctrine()
            ->getManager()
            ->createQueryBuilder();

        $qb->from( "AdminsBundle:".$this->entityName , $this->entityName );
        if ($txtKeywords) {
            $search = $qb->expr()->orX();
            foreach ( $this->searchKeys as $key ) {
                $search->add( $this->entityName.".$key like :key" );
            }
            $qb->where( $search )->setParameter( "key" , "%$txtKeywords%" );}
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ( $val == "" || !in_array( $key , $this->conditionKeys ) ) { continue; }
                $qb->andWhere( $this->entityName.".$key = :val" )
                    ->setParameter( "val" , $val );}}
        $qb->orderBy( $this->entityName.".orders" , "ASC" );
        //获取列表数目
        $qb->select( array( "COUNT(".$this->entityName.".id) as num" ) );
        $count = $qb->getQuery()->getSingleResult();
        //获取列表内容
        if ($count["num"] == 0) {
            $lists = array();
        }else{
            foreach ($this->listKeys as $key) {
                $select[] = $this->entityName.".".$key;
            }
            $qb->select($select);
            $qb->setFirstResult( $page * $per_page - $per_page );
            $qb->setMaxResults( $per_page );
            $lists = $qb->getQuery()->getResult();
        }
        return array(
            "total" => isset($count["num"]) ? $count["num"] : 0,
            "data"  => $lists
        );
    }
}